
var gUrl="http://rtqdev.morningstar.com/opt/test.jsp";
var gTable=document.getElementById("table");

function sendHttpRequest(){
	$.get(gUrl,null,function(response){onHttpComplete(response)});
}

function onHttpComplete(responseText){
		var jsonData;
		jsonData=JSON.parse(responseText);
		
		//get old price
		var oldPrice1=gTable.rows[1].cells[1].innerHTML;
		var oldPrice2=gTable.rows[3].cells[1].innerHTML;
		var oldCountPrice=gTable.rows[5].cells[1].innerHTML;
		
		//get new price
		var newPrice1=jsonData.ticker1;
		var newPrice2=jsonData.ticker2;
		var newCountPrice=newPrice1+newPrice2;
	
		//calculate other value
		var detailData1=getDetail(oldPrice1,newPrice1);
		var detailData2=getDetail(oldPrice2,newPrice2);
		var countDetailData=getDetail(oldCountPrice,newCountPrice);

		//set value for first ticker
		gTable.rows[1].cells[1].innerHTML=detailData1.newPrice;	
		var cell1=gTable.rows[1].cells[2];
		var cell2=gTable.rows[1].cells[3];
		changeCell(cell1,cell2,detailData1);
		
		//set value for second ticker
		gTable.rows[3].cells[1].innerHTML=detailData2.newPrice;
		var cell1=gTable.rows[3].cells[2];
		var cell2=gTable.rows[3].cells[3];
		changeCell(cell1,cell2,detailData2);
			
		//set count value
		gTable.rows[5].cells[1].innerHTML=countDetailData.newPrice;
		var cell1=gTable.rows[5].cells[2];
		var cell2=gTable.rows[5].cells[3];
		changeCell(cell1,cell2,countDetailData);
}

function changeCell(cell1,cell2,detailData){
	var newClass=detailData.difference>=0 ? "greencolor" :"redcolor";
	changeToClass(cell1,newClass);
	changeToClass(cell2,newClass);
	cell1.innerHTML=detailData.difference;
	cell2.innerHTML=detailData.percent;
}

function DetailData(newPrice,difference,percent){
	this.newPrice=newPrice;
	this.difference=difference;
	this.percent=percent;
}

function getDetail(oldPrice,newPrice){
	if(!oldPrice){
		oldPrice=newPrice;
	}
	var difference=(newPrice-oldPrice).toFixed(2);
	if(difference>0){
		difference="+"+difference;
	}
	var percent=((difference/oldPrice)*100).toFixed(2);
	if(percent>0){
		percent="+"+percent;
	}
	return new DetailData(newPrice.toFixed(2),difference,percent+"%");
}

function changeToClass(element,newClass){
	$(element).removeClass();
	$(element).addClass(newClass);
}

//checkbox click event handle
var gTimer;
function onCheckboxClick(){	
	checkbox=document.getElementById("checkbox");
	if(checkbox.checked){
		gTimer=window.setInterval(sendHttpRequest,10000);
	}else{
		window.clearInterval(gTimer);
	}
}

//table click event handle
function togglePic(event){
	rowIndex=event.target.parentNode.rowIndex;
	if(rowIndex%2==1 && rowIndex!=5){	
		$(gTable.rows[++rowIndex]).toggle();
	}
}

